include(RunCMake)

# Isolate from caller's environment.
unset(ENV{CMAKE_OSX_ARCHITECTURES})
unset(ENV{CMAKE_OSX_DEPLOYMENT_TARGET})
unset(ENV{SDKROOT})

function(run_xcode_cc)
  set(RunCMake_TEST_VARIANT_DESCRIPTION "-xcode")
  if(EXISTS "/usr/include/AvailabilityMacros.h")
    run_cmake(SDK)
  else()
    run_cmake(NoSDK)
  endif()
endfunction()

if(RunCMake_GENERATOR STREQUAL "Xcode")
  run_xcode_cc()
else()
  set(system_cc "/usr/bin/cc")
  set(system_cxx "/usr/bin/c++")
  if(EXISTS "${system_cc}" AND EXISTS "${system_cxx}")
    set(ENV{CC} "${system_cc}")
    set(ENV{CXX} "${system_cxx}")
    set(ENV{OBJC} "${system_cc}")
    set(ENV{OBJCXX} "${system_cxx}")
    set(RunCMake_TEST_VARIANT_DESCRIPTION "-system")
    run_cmake(SDK)
  endif()

  execute_process(COMMAND xcrun --find cc OUTPUT_VARIABLE xcode_cc OUTPUT_STRIP_TRAILING_WHITESPACE)
  execute_process(COMMAND xcrun --find c++ OUTPUT_VARIABLE xcode_cxx OUTPUT_STRIP_TRAILING_WHITESPACE)
  execute_process(COMMAND xcrun --show-sdk-path OUTPUT_VARIABLE xcode_sdk OUTPUT_STRIP_TRAILING_WHITESPACE)
  if(EXISTS "${xcode_cc}" AND EXISTS "${xcode_cxx}")
    set(ENV{CC} "${xcode_cc}")
    set(ENV{CXX} "${xcode_cxx}")
    set(ENV{OBJC} "${xcode_cc}")
    set(ENV{OBJCXX} "${xcode_cxx}")
    run_xcode_cc()
    if(EXISTS "${xcode_sdk}")
      set(RunCMake_TEST_VARIANT_DESCRIPTION "-xcode-SDKROOT")
      set(ENV{SDKROOT} "${xcode_sdk}")
      run_cmake(SDK)
      unset(ENV{SDKROOT})
    endif()
  endif()
endif()
